<template>
    <!-- 账户卡资料修改明细查询 -->
    <div class="accountCardDetaileQuery" v-loading="tableLoading">
        <cardComponent pageTitle="查询服务类-->账户/卡资料修改明细查询">
            <template slot="cardBody">
                <el-form
                    :model="searchFormOne"
                    size="small"
                    :inline="true"
                    label-position="right"
                    label-width="100px"
                    :rules="rules"
                    ref="formDate"
                    class="formData_form_inline"
                >
                    <el-row>
                        <el-form-item label="账户类别:" class="text_fl">
                            <el-select
                                v-model="searchFormOne.accttype"
                                placeholder="请选择账户类别"
                                clearable
                                @change="changeCardList"
                            >
                                <el-option
                                    v-for="item in AccountionTYPE_INFO"
                                    :label="item.label"
                                    :value="item.code"
                                    :key="item.label"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="卡号:" class="text_fl">
                            <el-select v-model="searchFormOne.cardno" placeholder="请选择卡号" clearable>
                                <el-option
                                    v-for="item in cardList"
                                    :label="item.CARDNBR"
                                    :value="item.CARDNBR"
                                    :key="item.CARDNBR"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="起始日期:" label-position="left" prop="startDate">
                            <el-date-picker
                                v-model="searchFormOne.startDate"
                                type="date"
                                placeholder="请选择起始日期"
                                format="yyyy-MM-dd"
                                value-format="yyyyMMdd"
                                :picker-options="startOptions"
                            ></el-date-picker>
                            <!-- <span class="Notice">YYYYMMMDDD</span> -->
                        </el-form-item>
                        <el-form-item label="结束日期:" label-position="left" prop="endDate">
                            <el-date-picker
                                v-model="searchFormOne.endDate"
                                type="date"
                                placeholder="请选择结束日期"
                                format="yyyy-MM-dd"
                                value-format="yyyyMMdd"
                                :picker-options="endtOptions"
                            ></el-date-picker>
                            <!-- <span class="Notice">YYYYMMMDDD</span> -->
                        </el-form-item>
                        <el-form-item>
                            <div class="btnBox">
                                <el-button
                                    type="primary"
                                    size="small"
                                    icon="el-icon-search"
                                    @click="handleIdQuery"
                                >按证件查询</el-button>
                                <el-button
                                    type="primary"
                                    size="small"
                                    @click="handleCardIdQuery"
                                    icon="el-icon-search"
                                >按卡查询</el-button>
                                <el-button
                                    type="primary"
                                    size="small"
                                    icon="el-icon-refresh-right"
                                    @click="restInfo"
                                >重置</el-button>
                            </div>
                        </el-form-item>
                    </el-row>
                </el-form>

                <div v-show="INQOPT === 2">
                    <el-table
                        :data="tableData"
                        width="100%"
                        border
                        stripe
                        class="heard-bg business_table"
                    >
                        <el-table-column label="修改日期" prop="DATE">
                            <template slot-scope="scoped">
                                <span>
                                    {{
                                    scoped.row.DATE
                                    | getFormatTime(scoped.row.TIME)
                                    }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="更改前值" prop="OLD">
                            <template slot-scope="scope">
                                <span>{{ scope.row.OLD | getType(scope.row.TYPE,updatedetailList) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="更改后值" prop="NEW">
                            <template slot-scope="scope">
                                <span>{{ scope.row.NEW | getType(scope.row.TYPE,updatedetailList) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="类型描述" prop="DISC"></el-table-column>
                        <el-table-column label="操作渠道" prop="BARNCH">
                            <template slot-scope="scoped">
                                <span>
                                    {{
                                    scoped.row.BARNCH
                                    | getBARNCH(OPERATESRC)
                                    }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作员工号" prop="EMPLOYEE">
                            <template slot-scope="scoped">
                                <span>
                                    {{
                                    scoped.row.EMPLOYEE
                                    | getCHNL(employeeList)
                                    }}
                                </span>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column label="备注" prop="ISPCS">
                            <template slot-scope="scoped">
                                <span>
                                    {{
                                    scoped.row.ISPCS
                                    | getISPCS(scoped.row.BARNCH)
                                    }}
                                </span>
                            </template>
                        </el-table-column>-->
                    </el-table>
                    <div class="footer">
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleChangePage('pre')"
                            :disabled="currentPageIndex <= 0"
                        >上一页</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleChangePage('next')"
                            :disabled="!nextButtonFlag"
                        >下一页</el-button>
                    </div>
                </div>
                <div v-show="INQOPT === 1">
                    <el-table
                        :data="tableDatas"
                        width="100%"
                        border
                        stripe
                        class="heard-bg business_table"
                    >
                        <el-table-column label="修改日期">
                            <template slot-scope="scope">
                                <span>
                                    <!-- {{ moment(scope.row.DATE).format("YYYY-MM-DD")}} -->
                                    {{
                                    scope.row.DATE | getDate(scope.row.TIME)
                                    }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="卡号末四位" prop="CARDNO">
                            <template slot-scope="scope">
                                <span>{{ scope.row.CARDNO | getSubString }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="更改前值" prop="OLD">
                            <template slot-scope="scope">
                                <span>{{ scope.row.OLD | getType(scope.row.TYPE,updatedetailList) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="更改后值" prop="NEW">
                            <template slot-scope="scope">
                                <span>{{ scope.row.NEW | getType(scope.row.TYPE,updatedetailList) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="类型描述" prop="DISC"></el-table-column>
                        <el-table-column label="操作渠道" prop="BARNCH">
                            <template slot-scope="scoped">
                                <span>
                                    {{
                                    scoped.row.BARNCH
                                    | getBARNCH(OPERATESRC)
                                    }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作员工号" prop="EMPLOYEE">
                            <template slot-scope="scoped">
                                <span>
                                    {{
                                    scoped.row.EMPLOYEE
                                    | getCHNL(employeeList)
                                    }}
                                </span>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column label="备注" prop="ISPCS">
                            <template slot-scope="scoped">
                                <span>
                                    {{
                                    scoped.row.ISPCS
                                    | getISPCS(scoped.row.BARNCH)
                                    }}
                                </span>
                            </template>
                        </el-table-column>-->
                    </el-table>
                    <!-- 话术 -->
                    <div class="hstable_wrap" v-if="speechList.length!=0">
                        <el-table
                            :data="speechList"
                            border
                            stripe
                            header-row-class-name="headerRow"
                            ref="showListTable"
                            class="heard-bg business_table hstable"
                            @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" label=" " min-width="55"></el-table-column>
                            <el-table-column label="业务话术">
                                <template slot-scope="scope">{{scope.row.content}}</template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="footer">
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleChangePage('pre')"
                            :disabled="currentPageIndex <= 0"
                        >上一页</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleChangePage('next')"
                            :disabled="!nextButtonFlag"
                        >下一页</el-button>
                    </div>
                </div>
            </template>
        </cardComponent>
    </div>
</template>

<script>
import moment from 'moment';
import { mapState, mapGetters } from 'vuex';
import cardComponent from '@/components/cardComponent/cardComponent.vue';
import { getDictSelectList, strZeroFill, myMoment } from '@/utils/Common';

export default {
    name: 'accountCardDetaileQuery',
    components: {
        cardComponent,
    },
    data() {
        return {
            cardList: [],
            searchFormOne: {
                accttype: '',
                cardno: '',
                cardId: '', // 证件号
                startDate: '20000101', // 开始日期 默认为当前日期往前一个月
                endDate: moment(new Date()).format('YYYYMMDD'), // 结束日期 默认为当前日期
            },
            OPERATESRC: [], // 操作渠道
            INQOPT: '', // 按证件还是卡号查询 1--按卡号查询  2--按证件号查询  3--按公司编号
            IDTYPE: '', // 证件种类查询方式为2时必填
            CUSTID: '', // 证件号码 查询方式为2-证件号码时，必填
            CODETYPE: '', // 分类查询
            carIdNumber: '',
            tableLoading: false, // 页面loading
            pagingDataList: [], // 分期付款申请编号(只存每页最后一条记录)
            currentPageIndex: '', // 当前页最后一条记录的申请编号的索引
            nextButtonFlag: false, // ‘下一页’  按钮的显示控制阀
            IDTYPEList: [], // 证件类型下拉
            // 表单下拉
            formSelect: [],
            tableData: [],//按证件号查询结果
            tableDatas: [],//按卡号查询结果
            rules: { // 表单校验规则
                startDate: [
                    { required: true, message: '请选择起始日期', trigger: 'blur' },
                ],
                endDate: [
                    { required: true, message: '请选择结束日期', trigger: 'blur' },
                ],
            },
            startOptions: { // 开始日期选择 限制
                disabledDate: (time) => {
                    if (this.searchFormOne.endDate) {
                        return time.getTime() > new Date(moment(this.searchFormOne.endDate).format('YYYY-MM-DD HH:mm:ss')).getTime();
                    }
                },
            },
            endtOptions: { // 结束日期选择限制
                disabledDate: (time) => {
                    if (this.searchFormOne.startDate) {
                        return time.getTime() < new Date(moment(this.searchFormOne.startDate).format('YYYY-MM-DD HH:mm:ss')).getTime();
                    }
                },
            },

            updatetypeList: [],//账户修改历史类型
            updatedetailList: [],// 账户修改历史详细类型列表
            employeeList: [],//操作员渠道列表
            speechList: [],//话术列表
            selectedList: [],


        };
    },
    async beforeCreate() {
        this.OPERATESRC = await getDictSelectList('OPERATESRC', this);
        this.IDTYPEList = await getDictSelectList('IDTYPE', this);
        console.log(this.IDTYPEList);
        this.updatetypeList = await getDictSelectList('UPDTYPE', this);
        this.employeeList = await getDictSelectList('EMPLOYEE', this);
        this.init();

    },
    filters: {
        // 拼接日期 时间
        getDate(date, time) {
            const resDate = moment(`${date}`).format('YYYY-MM-DD');
            const resTime = myMoment(time).format('HH:mm:ss');
            return `${resDate} ${resTime}`;
        },

        // 字符串截取
        getSubString(val) {
            const str = val.trim();
            return str.substring(str.length - 4);
        },
        // 时间处理
        getFormatTime(date, time) {
            let res = '';
            if (date) {
                res = moment(`${date}`).format('YYYY-MM-DD');
            }
            if (time) {
                res = `${res} ${myMoment(time).format('HH:mm:ss')}`;
            }
            return res;
        },
        // 操作渠道
        getBARNCH(val, OPERATESRC) {
            val = `${strZeroFill(val, 4)}`;
            let newVal;
            console.log("caozuoqudao:", val);
            for (let i = 0; i < OPERATESRC.length; i++) {
                let item = OPERATESRC[i];
                if (item.code + '' === val + '') {
                    newVal = item.label;
                    break;
                } else {
                    newVal = val;
                }
            }
            console.log("newVal", newVal);
            return newVal;
        },
        getISPCS(ISPCS, BARNCH) {
            // console.log(ISPCS)
            // console.log(BARNCH)
            let text = '';
            if (ISPCS === '9999' && BARNCH === 'MBKQ0') {
                text = '客服IVR';
            } else {
                text = '';
                return;
            }
            return text;
        },

        //修改前、后的值
        getType(val, type, updatedetailList) {
            //console.log("val:" + val.trim() + "|type:" + type + "|");
            let txt = val;
            updatedetailList.some((item) => {
                if (item.dictValue === type.trim() && item.code === val.trim()) {
                    txt = item.label;
                    return true;
                } else {
                    if ((type + '' === 'CD01' || type + '' === 'CD13' || type + '' === 'AC04' || type + '' === 'CDCL' || type + '' === 'CD02' || type + '' === 'ACA4') && val.trim() === '') {
                        txt = '正常';
                        // console.log("type:" + type + ",txt:" + txt);
                        return true;
                    }
                }
            });
            if (type === 'PR01') {//补寄账单，翻译账单寄送方式
                let stmtp = val.substring(5, 6);
                console.log("stmtp", stmtp);
                if (stmtp === '0') {
                    txt = val.substring(0, 4) + ' 纸质账单 ' + val.substring(7, 8);
                } else if (stmtp === '1') {
                    txt = val.substring(0, 4) + ' 电子账单 ' + val.substring(7, 8);
                }
            }
            // console.log("val:" + val.trim() + "|type:" + type + "|txt:" + txt + "|");
            return txt;

        },
        getCHNL(val, employeeList) {
            let txt = val;
            console.log("employeeList:", employeeList);
            employeeList.some((item) => {
                if (item.code + '' === val + '') {
                    // console.log("item:", item);
                    txt = item.label;
                    return true;
                }
            });
            // console.log("val:" + val + "|txt:" + txt + "|");
            return txt;
        },
    },
    mounted() {
        this.searchFormOne.CARDNO = this.cardInfo_3004.CARDNO;
        this.searchFormOne.cardId = this.cardInfo_3004.CUSTID;
        this.IDTYPE = this.cardInfo_3004.KEYTYPE;
        //this.getQueryCategory();

        this.changeCardList(this.cardInfo_3004.CATEGORY + '');
    },
    computed: {
        ...mapState({
            defaultParams: state => state.common.defaultParams,
            cardInfo_3004: state => state.common.cardInfo_3004,
            defaultpinFlag: state => state.common.pinFlag,
            AccountionTYPE_INFO: state => state.common.AccountionTYPE_INFO, //账户类别列表
            cardList_3601: state => state.common.cardList_3601, //卡列表
            isCurrentMenuInfo: state => state.menu.isCurrentMenuInfo,
        }),

    },
    methods: {

        async init() {
            this.MenuId = this.$route.params.id || '';
            console.log("this.OPERATESRC", this.OPERATESRC);

            for (let i = 0; i < this.updatetypeList.length; i++) {
                // console.log(i + '-' + this.updatetypeList[i].code);
                let newlist = await getDictSelectList(this.updatetypeList[i].code, this);
                this.updatedetailList.push(...newlist)
                //console.log("this.updatedetailList", this.updatedetailList);
            }

            console.log("默认账户类别：" + this.cardInfo_3004.CATEGORY);
            console.log("默认账户：" + this.cardInfo_3004.CARDNO);
            this.searchFormOne.accttype = this.cardInfo_3004.CATEGORY + '';
            await this.getspeechList();
        },
        changeCardList(val) {
            console.log("当前账户类型：" + val);
            let hasDefault = false; //是否包含默认卡
            this.cardList = [];
            this.cardList_3601.forEach((item) => {
                if (item.CATEGORY + '' === val) {
                    this.cardList.push(item);
                    if (item.CARDNBR === this.cardInfo_3004.CARDNO) {
                        hasDefault = true;
                    }
                }
            });

            //包含默认卡，卡号显示默认卡，不包含，显示cardList里第一张卡号
            if (hasDefault) {
                this.searchFormOne.cardno = this.cardInfo_3004.CARDNO;
            } else {
                this.searchFormOne.cardno = this.cardList[0].CARDNBR;
            }


        },
        //根据菜单id查询话术列表
        async getspeechList() {
            console.log("this.isCurrentMenuInfo.id", this.isCurrentMenuInfo.id);
            console.log("this.MenuId", this.MenuId);
            var checkParam = {
                'id': this.MenuId || this.isCurrentMenuInfo.id,
            };
            this.$post.busiMenu.getlistByMenuId(checkParam).then((res) => {
                console.log("话术查询结果：", res);
                if (res.status === 200) { // http通讯成功
                    if (res.data.status == 0) { // 业务请求成功
                        this.speechList = res.data.content;
                    }
                }
            });
        },
        handleSelectionChange(val) {
            this.selectedList = val;
        },
        // 查询类别
        getQueryCategory() {
            this.$post.instalment.getDictValueList({ dictValue: 'CODETYPE' })
                .then((res) => {
                    if (res.status === 200) {
                        this.formSelect = res.data.content || [];
                        this.CODETYPE = '';
                    }
                });
        },
        // 按证件查询
        handleIdQuery() {

            this.$refs.formDate.validate((valid) => {
                if (valid) {
                    this.INQOPT = 2;
                    this.tableData = [];
                    this.pagingDataList = [];
                    this.getQueryInfo();
                } else {

                }
            });
        },
        // 按卡查询
        handleCardIdQuery() {

            if (this.searchFormOne.cardno === '') {
                this.$alert('请先选择账户类别和卡号！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                return;
            }
            this.$refs.formDate.validate((valid) => {
                if (valid) {
                    this.INQOPT = 1;
                    this.tableDatas = [];
                    this.pagingDataList = [];
                    this.getQueryInfo();
                } else {

                }
            });
        },
        getQueryInfo() {
            // 设置请求参数 -- 3020 交易
            let DATE = '';
            let TIME = '';
            let TYPE = '';
            let SEQ = '';
            let ISPCS = '';
            if (this.pagingDataList.length) { // 判断翻页上传字段取值
                DATE = this.pagingDataList[this.currentPageIndex].DATE;
                TIME = this.pagingDataList[this.currentPageIndex].TIME;
                TYPE = this.pagingDataList[this.currentPageIndex].TYPE;
                SEQ = this.pagingDataList[this.currentPageIndex].SEQ;
                ISPCS = this.pagingDataList[this.currentPageIndex].ISPCS;
            }
            this.tableLoading = true;
            const appBody = {
                CARDNBR: this.searchFormOne.cardno || '', // 卡号
                OPT: '1', // 查询方式 1-卡号查询  2-证件号查询
                PINFLAG: this.defaultpinFlag, // 是否检查密码标志
                PIN: '', // 密码
                INQOPT: this.INQOPT, // 按证件还是卡号查询 1--按卡号查询  2--按证件号查询  3--按公司编号,
                // IDTYPE: 20, //证件种类查询方式为2时必填
                IDTYPE: this.IDTYPE, // 证件种类查询方式为2时必填
                CUSTID: this.searchFormOne.cardId, // 证件号码 查询方式为2-证件号码时，必填
                CODETYPE: this.CODETYPE, // 分类查询
                STARTDATE: this.searchFormOne.startDate, // 起始日期
                ENDDATE: this.searchFormOne.endDate, // 结束日期
                RTNIND: this.pagingDataList.length === 0 ? '' : 1, // 翻页标志 首次传空， 翻页传1
                DATE, // YYYYMMDD 翻页控制使用；首次查询上送空；翻页查询时上送上页返回的最后一条记录的登记日期；
                TIME, // HHMMSShh 翻页控制使用；首次查询上送空；翻页查询时上送上页返回的最后一条记录登记时间；
                TYPE, // 翻页控制使用；首次查询上送空；翻页查询时上送上页返回的最后一条记录的类型；
                SEQ, // 翻页控制使用；首次查询上送空；翻页查询时上送上页返回的最后一条记录序号；
                ISPCS, // 翻页控制使用；首次查询上送空；翻页查询时上送上页返回的最后一条记录的登记画面；
            };
            console.log("appBody", appBody);
            const defaultParams = JSON.parse(JSON.stringify(this.defaultParams));
            defaultParams.body.appHead.tranCode = '3020';
            defaultParams.body.appBody = appBody;
            // console.log(this.OPERATESRC)

            // 跑3020交易
            this.$post.common.transPort(defaultParams).then((res) => {
                this.tableLoading = false;
                if (res.status === 200) {
                    const result = JSON.parse(res.data.jsonRes);
                    // console.log(result, '返回结果')
                    if (result.sysHead.rspCd === '000000') {
                        if (this.INQOPT === 2) {
                            this.tableData = result.body.appBody.dataList || [];
                        } else if (this.INQOPT === 1) {
                            this.tableDatas = result.body.appBody.dataList || [];
                        }

                        // 判断此次查询数据最后一条记录申请编号是否在已有列表中  没有- 添加
                        const currentAppref = result.body.appBody.dataList[result.body.appBody.dataList.length - 1].APPREF;
                        const newObj = result.body.appBody.dataList[result.body.appBody.dataList.length - 1];
                        const currentPagingData = {
                            DATE: newObj.DATE,
                            TIME: newObj.TIME,
                            TYPE: newObj.TYPE,
                            SEQ: newObj.SEQ,
                            ISPCS: newObj.ISPCS,
                        };
                        console.log(result, '返回结果');
                        this.nextButtonFlag = !(result.body.appBody.RTNIND === '0');
                        let flag = false;
                        let currentIndex;
                        this.pagingDataList.forEach((item, index) => { // 判断此次查询数据最后一条记翻页分期付款序号是否在已有列表中
                            if (item.TIME === currentPagingData.TIME && item.DATE === currentPagingData.DATE &&
                                item.TYPE === currentPagingData.TYPE && item.SEQ === currentPagingData.SEQ && item.ISPCS === currentPagingData.ISPCS) {
                                flag = true;
                                currentIndex = index;
                            }
                        });
                        if (flag) { // 存在
                            this.currentPageIndex = currentIndex;
                        } else {
                            this.pagingDataList.push(currentPagingData);
                            this.currentPageIndex = this.pagingDataList.length - 1;
                        }
                        console.log(" this.pagingDataList", this.pagingDataList);
                    } else {
                        const errorMsg = `错误代码：${result.sysHead.rspCd}, 错误信息：${result.sysHead.rspMsg}`;
                        this.$alert(errorMsg, '提示', {
                            customClass: 'error', type: 'error',
                        });
                        this.tableData = [];
                    }
                } else {
                    this.$alert('请求失败！', '提示', {
                        customClass: 'error', type: 'error',
                    });
                }
            });
        },
        // 上下页切换
        handleChangePage(type) {
            if (type === 'pre') { // 切换到上一页
                console.log("this.currentPageIndex", this.currentPageIndex);
                if (this.currentPageIndex - 2 < 0) {
                    this.pagingDataList = []; // 清空缓存 申请编号 -> 相当于首次查询
                } else {
                    this.currentPageIndex = this.currentPageIndex - 2;
                }
                this.getQueryInfo();
            } else { // 切换到下一页
                this.getQueryInfo();
            }
        },
        // 重置按钮，重置
        restInfo() {
            this.CODETYPE = '';
            this.searchFormOne.startDate = '20000101';
            this.searchFormOne.endDate = moment(new Date()).format('YYYYMMDD');
            this.tableData = [];
            this.INQOPT = '';
        },

    },
};
</script>

<style lang='scss'>
.accountCardDetaileQuery {
    width: 98%;
    background: #fff;
    // padding:10px;
    box-sizing: border-box;
    border-radius: 5px;

    .el-input,
    .el-date-editor {
        width: 100%;
    }
    /* //头部内容 */
    .tab-header {
        width: 100%;
        text-align: left;
        span {
            font-size: 14px;
        }
        .headerTitle {
            font-size: 16px;
            margin: 10px 0px;
            color: skyblue;
        }
        .el-form-item__content {
            text-align: left;
        }
    }
    .btnBox {
        margin: 0 0 0 0px;
        text-align: center;
    }
    .footer {
        margin-top: 32px;
        text-align: center;
    }
}
</style>
